package kr.pe.johnkim.app.mobile.rest.controller;

import kr.pe.johnkim.app.domain.MyHistoryLog;
import kr.pe.johnkim.app.mobile.rest.service.MyHistoryCommonService;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;

/**
 * @author : johnkim <cale9797@gmail.com / Bettersoft Inc,.>
 * @Date : 12. 2. 6
 */
@Controller
@Path("/myHistoryCommonController")
public class MyHistoryCommonController {
    // SLF4J Logging
	private Logger logger = LoggerFactory.getLogger(MyHistoryCommonController.class);

    @Autowired
    private MyHistoryCommonService myHistoryCommonService = null;

    /**
     * 로그를 등록 한다.
     * 
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/registerLog")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public Response registerLog(InputStream is) throws IOException, JSONException {
        logger.info("registerLog");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonLog = new JSONObject(line);
        JSONObject jsonLog2 = jsonLog.getJSONObject("myHistoryLog");

        MyHistoryLog parameterLog = new MyHistoryLog();

        parameterLog.setId(jsonLog2.getString("id"));
        parameterLog.setViewName(jsonLog2.getString("viewName"));
        parameterLog.setAccessDate(jsonLog2.getString("accessDate"));

        logger.info("id         : {}", parameterLog.getId());
        logger.info("viewName   : {}", parameterLog.getViewName());
        logger.info("accessDate : {}", parameterLog.getAccessDate());

        myHistoryCommonService.registerLog(parameterLog);

        return Response.created(URI.create("/myHistoryLog/" + parameterLog.getIdMyHistoryLogs())).build();
    }
}
